package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.user.client.VipServiceConfigFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VipServiceConfigFeignClient vipServiceConfigFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //1、设置交易号 支付类型 订单类型
        //设置交易号
        String tradeNo = IdWorker.getIdStr();//雪花算法生成交易号
        orderInfoVo.setTradeNo(tradeNo);
        //1.1保存到redis  保证幂等性
        this.redisTemplate.opsForValue().set(RedisConstant.ORDER_IDEM_PREFIX+tradeNo,"",RedisConstant.IDEM_TIMEOUT, TimeUnit.SECONDS);
        //1.2支付方式
        orderInfoVo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        //1.3订单类型
        orderInfoVo.setItemType(tradeVo.getItemType());
        //判断订单类型
        if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(orderInfoVo.getItemType())){//专辑购买 下订单
            //根据专辑id查询专辑
            Result<AlbumInfo> albumInfoResult = this.albumInfoFeignClient.getAlbumInfo(tradeVo.getItemId());
            Assert.notNull(albumInfoResult,"专辑订单确认页面，远程调用查询专辑失败");
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo,"专辑订单确认页面，该专辑不存在"+albumInfo.getId());

            //获取登录状态userId
            Long userId = AuthContextHolder.getUserId();
            //根据userId查询用户
            Result<UserInfo> userInfoByIdResult = this.userInfoFeignClient.getUserInfoById(userId);
            Assert.notNull(userInfoByIdResult,"专辑订单确认页面，远程调用查询用户失败");
            UserInfo userInfo = userInfoByIdResult.getData();
            Assert.notNull(userInfo,"专辑订单确认页面，用户不存在"+userInfo.getId());
            //判断用户vip状态        普通用户折扣   vip用户折扣
            BigDecimal discount = new BigDecimal(-1);
            if (userInfo.getIsVip().equals(1)&&userInfo.getVipExpireTime().after(new Date())){
                discount = albumInfo.getVipDiscount();
            }else {
                discount = albumInfo.getDiscount();
            }


            //如果是-1 说明不打折 取10
            if (discount.compareTo(new BigDecimal(-1))==0){
                discount = new BigDecimal(10);
            }

            //计算价格参数
            //原价
            BigDecimal originalAmount = albumInfo.getPrice();
            //打折多少 价格
            BigDecimal orderAmount = originalAmount.multiply(discount).divide(new BigDecimal(10));
            BigDecimal derateAmount = originalAmount.subtract(orderAmount);

            orderInfoVo.setOriginalAmount(originalAmount);
            orderInfoVo.setOrderAmount(orderAmount);
            orderInfoVo.setDerateAmount(derateAmount);
            //组装订单详情

            //组装订单详情信息 vip订单只有一个
            orderInfoVo.setOrderDetailVoList((Arrays.asList(
                    new OrderDetailVo().setItemId(albumInfo.getId())
                            .setItemName(albumInfo.getAlbumTitle())
                            .setItemUrl(albumInfo.getCoverUrl()).setItemPrice(orderInfoVo.getOrderAmount())
            )));
            //组装减免信息
            orderInfoVo.setOrderDerateVoList(List.of(new OrderDerateVo()
                    .setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT)
                    .setDerateAmount(orderInfoVo.getDerateAmount())
            ));

        }else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(orderInfoVo.getItemType())){

        }else if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(orderInfoVo.getItemType())){//根据订单类型设置参数  vip套餐购买

            //根据套餐id查询Vip套餐  远程调用user服务
            Result<VipServiceConfig> vipServiceConfigResult = this.vipServiceConfigFeignClient.getVipServiceConfig(tradeVo.getItemId());
            Assert.notNull(vipServiceConfigResult,"返回订单详细信息，远程调用根据套餐id查询套餐失败");
            VipServiceConfig vipServiceConfig = vipServiceConfigResult.getData();
            Assert.notNull(vipServiceConfig,"vip订单确认页，对应的vip套餐不存在" + tradeVo.getItemId());

            //设置三个价格字段 originalAmount  derateAmount orderAmount
            orderInfoVo.setOriginalAmount(vipServiceConfig.getPrice());//原价
            orderInfoVo.setDerateAmount(vipServiceConfig.getDiscountPrice());//减免金额
            orderInfoVo.setOrderAmount(vipServiceConfig.getPrice().subtract(vipServiceConfig.getDiscountPrice()));


            //组装订单详情信息 vip订单只有一个
            orderInfoVo.setOrderDetailVoList((Arrays.asList(
                    new OrderDetailVo().setItemId(vipServiceConfig.getId())
                            .setItemName(vipServiceConfig.getName())
                            .setItemUrl(vipServiceConfig.getImageUrl()).setItemPrice(orderInfoVo.getOrderAmount())
            )));
            //组装减免信息
            orderInfoVo.setOrderDerateVoList(List.of(new OrderDerateVo()
                            .setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT)
                    .setDerateAmount(orderInfoVo.getDerateAmount())
                    ));

            //生成时间戳和签名 防止用户篡改订单确认页的信息，

        }

        orderInfoVo.setTimestamp(SignHelper.getTimestamp());
        orderInfoVo.setSign(SignHelper.getSign(JSON.parseObject(JSON.toJSONString(orderInfoVo), HashMap.class)));


        return  orderInfoVo;
    }
}
